<template>
  <div class="enter-out-analysis">
    <el-card class="header-card">
      <div class="header-content">
        <h2>出入库实时分析</h2>
        <div class="connection-status">
          <el-tag :type="connectionStatus ? 'success' : 'danger'" size="large">
            {{ connectionStatus ? "已连接" : "未连接" }}
          </el-tag>
          <el-button
            v-if="!connectionStatus"
            @click="connectSignalR"
            type="primary"
            size="small"
          >
            重新连接
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon in-icon">
            <el-icon><ArrowUp /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ analysisData.totalIn }}</div>
            <div class="stat-label">总入库量</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon out-icon">
            <el-icon><ArrowDown /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ analysisData.totalOut }}</div>
            <div class="stat-label">总出库量</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon net-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-info">
            <div
              class="stat-value"
              :class="{
                positive: analysisData.netChange > 0,
                negative: analysisData.netChange < 0,
              }"
            >
              {{ analysisData.netChange > 0 ? "+" : ""
              }}{{ analysisData.netChange }}
            </div>
            <div class="stat-label">净变化</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>每日出入库趋势</span>
              </div>
            </template>
            <div class="chart-container">
              <v-chart :option="dailyChartOption" style="height: 300px" />
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>仓库统计</span>
              </div>
            </template>
            <div class="chart-container">
              <v-chart :option="warehouseChartOption" style="height: 300px" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 实时数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>实时出入库记录</span>
          <el-button @click="refreshData" type="primary" size="small">
            刷新数据
          </el-button>
          <el-button @click="testData" type="warning" size="small">
            测试数据
          </el-button>
          <el-button @click="testSignalR" type="info" size="small">
            测试SignalR
          </el-button>
          <el-button @click="debugDataMapping" type="warning" size="small">
            调试数据映射
          </el-button>
          <el-button @click="debugSignalRConnection" type="danger" size="small">
            调试SignalR连接
          </el-button>
        </div>
      </template>

      <el-table :data="enterOutData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="Warehouse_Code" label="单号" />
        <el-table-column
          prop="WarehouseInOrOutCount"
          label="数量"
          width="100"
        />
        <el-table-column prop="WarehouseType" label="类型" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.WarehouseType === 1 ? 'success' : 'danger'"
            >
              {{ scope.row.WarehouseType === 1 ? "入库" : "出库" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="Warehouse_Name" label="仓库" width="120" />
        <el-table-column prop="Warehousing_Type" label="类型名称" width="120" />
        <el-table-column prop="CreateTime" label="日期时间" width="180" />
        <el-table-column prop="Total_Price" label="金额" width="100" />
      </el-table>
    </el-card>

    <!-- 热门产品统计 -->
    <el-card class="top-products-card">
      <template #header>
        <div class="card-header">
          <span>热门产品统计</span>
        </div>
      </template>

      <div class="top-products-list">
        <div
          v-for="(product, index) in analysisData.topProducts"
          :key="index"
          class="product-item"
        >
          <div class="product-rank">{{ index + 1 }}</div>
          <div class="product-info">
            <div class="product-name">{{ product.productName }}</div>
            <div class="product-quantity">
              数量: {{ product.totalQuantity }}
              <el-tag
                :type="product.type === '入库' ? 'success' : 'danger'"
                size="small"
              >
                {{ product.type }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { ArrowUp, ArrowDown, TrendCharts } from "@element-plus/icons-vue";
import VChart from "vue-echarts";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { LineChart, BarChart, PieChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import {
  signalRService,
  type EnterOutDTO,
  type AnalysisData,
} from "@/router/ware";

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

// 响应式数据
const connectionStatus = ref(false);
const loading = ref(false);
const enterOutData = ref<EnterOutDTO[]>([]);
const analysisData = reactive<AnalysisData>({
  totalIn: 0,
  totalOut: 0,
  netChange: 0,
  dailyStats: [],
  topProducts: [],
  warehouseStats: [],
});

// 计算图表选项
const dailyChartOption = computed(() => {
  // 如果没有数据，显示默认图表
  if (analysisData.dailyStats.length === 0) {
    return {
      title: {
        text: "每日出入库趋势",
        left: "center",
        textStyle: {
          color: "#666",
        },
      },
      tooltip: {
        trigger: "axis",
      },
      legend: {
        data: ["入库", "出库"],
        top: 30,
      },
      xAxis: {
        type: "category",
        data: ["暂无数据"],
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          name: "入库",
          type: "line",
          data: [0],
          itemStyle: { color: "#67C23A" },
        },
        {
          name: "出库",
          type: "line",
          data: [0],
          itemStyle: { color: "#F56C6C" },
        },
      ],
    };
  }

  return {
    title: {
      text: "每日出入库趋势",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["入库", "出库"],
      top: 30,
    },
    xAxis: {
      type: "category",
      data: analysisData.dailyStats.map((item) => item.date),
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "入库",
        type: "line",
        data: analysisData.dailyStats.map((item) => item.inCount),
        itemStyle: { color: "#67C23A" },
        smooth: true,
      },
      {
        name: "出库",
        type: "line",
        data: analysisData.dailyStats.map((item) => item.outCount),
        itemStyle: { color: "#F56C6C" },
        smooth: true,
      },
    ],
  };
});

const warehouseChartOption = computed(() => ({
  title: {
    text: "仓库出入库统计",
    left: "center",
  },
  tooltip: {
    trigger: "item",
  },
  legend: {
    orient: "vertical",
    left: "left",
  },
  series: [
    {
      name: "仓库统计",
      type: "pie",
      radius: "50%",
      data: analysisData.warehouseStats.map((item) => ({
        name: item.warehouse,
        value: item.inCount + item.outCount,
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)",
        },
      },
    },
  ],
}));

onMounted(() => {
  connectSignalR();
});

// 连接SignalR
const connectSignalR = async () => {
  try {
    loading.value = true;
    console.log("开始连接SignalR...");

    await signalRService.createConnection();
    connectionStatus.value = signalRService.getConnectionStatus();

    console.log("SignalR连接状态:", connectionStatus.value);

    if (!connectionStatus.value) {
      throw new Error("SignalR连接失败");
    }

    // 监听出入库数据
    signalRService.onReceiveEnterOutData((data: any) => {
      console.log("=== 收到SignalR数据 ===");
      console.log("原始数据类型:", typeof data);
      console.log("是否为数组:", Array.isArray(data));
      console.log("原始数据:", JSON.stringify(data, null, 2));

      let processedData: EnterOutDTO[] = [];
      if (Array.isArray(data)) {
        console.log("处理数组数据，长度:", data.length);
        processedData = data.map((item, index) => {
          // 根据后端返回的小写字段名进行映射
          const processed: EnterOutDTO = {
            id: item.id || item.Id || 0,
            WarehouseType: item.warehouseType || item.WarehouseType || 1,
            Warehouse_Code: item.warehouse_Code || item.Warehouse_Code || "",
            Warehousing_Type:
              item.warehousing_Type || item.Warehousing_Type || "",
            OrderCode: item.orderCode || item.OrderCode || "",
            SupplierCode: item.supplierCode || item.SupplierCode || "",
            SupplierName: item.supplierName || item.SupplierName || "",
            Supplier_Contacts:
              item.supplier_Contacts || item.Supplier_Contacts || "",
            Supplier_Phone: item.supplier_Phone || item.Supplier_Phone || "",
            Purchase_Id: item.purchase_Id || item.Purchase_Id || 0,
            Purchase_Number: item.purchase_Number || item.Purchase_Number || "",
            Sell_Id: item.sell_Id || item.Sell_Id || 0,
            Sell_Number: item.sell_Number || item.Sell_Number || "",
            Product_Id: item.product_Id || item.Product_Id || 0,
            Product_Number: item.product_Number || item.Product_Number || "",
            Product_Name: item.product_Name || item.Product_Name || "",
            Specifications: item.specifications || item.Specifications || "",
            Batch: item.batch || item.Batch || "",
            Price: item.price || item.Price || "",
            WarehouseInOrOutCount:
              item.warehouse_InOrOutCount || item.WarehouseInOrOutCount || 0,
            Total_Price: item.total_Price || item.Total_Price || 0,
            Warehouse_ID: item.warehouse_ID || item.Warehouse_ID || 0,
            Warehouse_Name: item.warehouse_Name || item.Warehouse_Name || "",
            Storage_ID: item.storage_ID || item.Storage_ID || 0,
            Storage_Name: item.storage_Name || item.Storage_Name || "",
            Notes: item.notes || item.Notes || "",
            State: item.state || item.State || "",
            Reviewer: item.reviewer || item.Reviewer || "",
            Reason: item.reason || item.Reason || "",
            ReviewTime: item.reviewTime || item.ReviewTime || "",
            CreateUse: item.createUse || item.CreateUse || 0,
            UpdateUse: item.upDateUse || item.UpdateUse || 0, // 注意：后端返回的是upDateUse
            CreateTime: item.createTime || item.CreateTime || "",
            UpdateTime: item.upDataTime || item.UpdateTime || "", // 注意：后端返回的是upDataTime
            IsDeleted: item.isDeleted || item.IsDeleted || false,
          };
          console.log(`处理第${index + 1}条数据:`, processed);
          return processed;
        });
      } else if (data && typeof data === "object") {
        console.log("处理单个对象数据");
        processedData = [
          {
            id: data.id || data.Id || 0,
            WarehouseType: data.warehouseType || data.WarehouseType || 1,
            Warehouse_Code: data.warehouse_Code || data.Warehouse_Code || "",
            Warehousing_Type:
              data.warehousing_Type || data.Warehousing_Type || "",
            OrderCode: data.orderCode || data.OrderCode || "",
            SupplierCode: data.supplierCode || data.SupplierCode || "",
            SupplierName: data.supplierName || data.SupplierName || "",
            Supplier_Contacts:
              data.supplier_Contacts || data.Supplier_Contacts || "",
            Supplier_Phone: data.supplier_Phone || data.Supplier_Phone || "",
            Purchase_Id: data.purchase_Id || data.Purchase_Id || 0,
            Purchase_Number: data.purchase_Number || data.Purchase_Number || "",
            Sell_Id: data.sell_Id || data.Sell_Id || 0,
            Sell_Number: data.sell_Number || data.Sell_Number || "",
            Product_Id: data.product_Id || data.Product_Id || 0,
            Product_Number: data.product_Number || data.Product_Number || "",
            Product_Name: data.product_Name || data.Product_Name || "",
            Specifications: data.specifications || data.Specifications || "",
            Batch: data.batch || data.Batch || "",
            Price: data.price || data.Price || "",
            WarehouseInOrOutCount:
              data.warehouse_InOrOutCount || data.WarehouseInOrOutCount || 0,
            Total_Price: data.total_Price || data.Total_Price || 0,
            Warehouse_ID: data.warehouse_ID || data.Warehouse_ID || 0,
            Warehouse_Name: data.warehouse_Name || data.Warehouse_Name || "",
            Storage_ID: data.storage_ID || data.Storage_ID || 0,
            Storage_Name: data.storage_Name || data.Storage_Name || "",
            Notes: data.notes || data.Notes || "",
            State: data.state || data.State || "",
            Reviewer: data.reviewer || data.Reviewer || "",
            Reason: data.reason || data.Reason || "",
            ReviewTime: data.reviewTime || data.ReviewTime || "",
            CreateUse: data.createUse || data.CreateUse || 0,
            UpdateUse: data.upDateUse || data.UpdateUse || 0, // 注意：后端返回的是upDateUse
            CreateTime: data.createTime || data.CreateTime || "",
            UpdateTime: data.upDataTime || data.UpdateTime || "", // 注意：后端返回的是upDataTime
            IsDeleted: data.isDeleted || data.IsDeleted || false,
          },
        ];
      }

      console.log("=== 最终处理后的数据 ===");
      console.log("处理后的数据:", processedData);
      console.log("数据长度:", processedData.length);

      enterOutData.value = processedData;
      updateAnalysisData(processedData);
      ElMessage.success(`收到 ${processedData.length} 条真实数据`);
    });

    // 监听连接状态变化
    const checkConnection = () => {
      const currentStatus = signalRService.getConnectionStatus();
      if (currentStatus !== connectionStatus.value) {
        console.log(
          "连接状态变化:",
          connectionStatus.value,
          "->",
          currentStatus
        );
        connectionStatus.value = currentStatus;

        // 如果连接断开，尝试重新连接
        if (!currentStatus) {
          console.log("连接断开，尝试重新连接...");
          setTimeout(async () => {
            try {
              await signalRService.createConnection();
              connectionStatus.value = signalRService.getConnectionStatus();
              console.log("重新连接成功");
            } catch (error) {
              console.error("重新连接失败:", error);
            }
          }, 2000);
        }
      }
    };

    // 定期检查连接状态
    const connectionCheckInterval = setInterval(checkConnection, 3000);

    // 在组件卸载时清理定时器
    onUnmounted(() => {
      clearInterval(connectionCheckInterval);
    });

    ElMessage.success("SignalR连接成功");
  } catch (error) {
    console.error("连接失败:", error);
    ElMessage.error("SignalR连接失败");
  } finally {
    loading.value = false;
  }
};

// 更新分析数据
const updateAnalysisData = (data: EnterOutDTO[]) => {
  console.log("开始更新分析数据，数据长度:", data.length);

  // 计算总入库和出库量
  const inData = data.filter((item) => item.WarehouseType === 1); // 1表示入库
  const outData = data.filter((item) => item.WarehouseType === 2); // 2表示出库

  console.log("入库数据数量:", inData.length);
  console.log("出库数据数量:", outData.length);

  analysisData.totalIn = inData.reduce(
    (sum, item) => sum + (item.WarehouseInOrOutCount || 0),
    0
  );
  analysisData.totalOut = outData.reduce(
    (sum, item) => sum + (item.WarehouseInOrOutCount || 0),
    0
  );
  analysisData.netChange = analysisData.totalIn - analysisData.totalOut;

  // 按日期分组统计
  const dailyMap = new Map();
  data.forEach((item) => {
    if (!item.CreateTime) {
      console.warn("数据缺少CreateTime字段:", item);
      return;
    }
    const date = item.CreateTime.split(" ")[0]; // 只取日期部分
    if (!dailyMap.has(date)) {
      dailyMap.set(date, { inCount: 0, outCount: 0, netChange: 0 });
    }
    const stats = dailyMap.get(date);
    if (item.WarehouseType === 1) {
      // 入库
      stats.inCount += item.WarehouseInOrOutCount || 0;
    } else if (item.WarehouseType === 2) {
      // 出库
      stats.outCount += item.WarehouseInOrOutCount || 0;
    }
    stats.netChange = stats.inCount - stats.outCount;
  });

  analysisData.dailyStats = Array.from(dailyMap.entries()).map(
    ([date, stats]) => ({
      date,
      inCount: stats.inCount,
      outCount: stats.outCount,
      netChange: stats.netChange,
    })
  );

  // 按仓库分组统计
  const warehouseMap = new Map();
  data.forEach((item) => {
    const warehouseName = item.Warehouse_Name || "未知仓库";
    if (!warehouseMap.has(warehouseName)) {
      warehouseMap.set(warehouseName, { inCount: 0, outCount: 0 });
    }
    const stats = warehouseMap.get(warehouseName);
    if (item.WarehouseType === 1) {
      // 入库
      stats.inCount += item.WarehouseInOrOutCount || 0;
    } else if (item.WarehouseType === 2) {
      // 出库
      stats.outCount += item.WarehouseInOrOutCount || 0;
    }
  });

  analysisData.warehouseStats = Array.from(warehouseMap.entries()).map(
    ([warehouse, stats]) => ({
      warehouse,
      inCount: stats.inCount,
      outCount: stats.outCount,
    })
  );

  // 热门产品统计
  const productMap = new Map();
  data.forEach((item) => {
    const productName = item.Product_Name || item.Warehouse_Code || "未知产品";
    const key = `${productName}_${item.WarehouseType}`;
    if (!productMap.has(key)) {
      productMap.set(key, {
        productName: productName,
        totalQuantity: 0,
        type: item.WarehouseType === 1 ? "入库" : "出库",
      });
    }
    productMap.get(key).totalQuantity += item.WarehouseInOrOutCount || 0;
  });

  analysisData.topProducts = Array.from(productMap.values())
    .sort((a, b) => b.totalQuantity - a.totalQuantity)
    .slice(0, 10);
};

// 刷新数据
const refreshData = () => {
  if (enterOutData.value.length > 0) {
    updateAnalysisData(enterOutData.value);
    ElMessage.success("数据已刷新");
  }
};

// 测试数据
const testData = () => {
  console.log("=== 生成测试数据 ===");

  // 生成模拟数据，使用与后端一致的数据结构（小写字段名）
  const mockBackendData = [
    {
      id: 1,
      warehouseType: 1, // 入库
      warehouse_Code: "WH001",
      warehousing_Type: "采购入库",
      orderCode: "PO001",
      supplierCode: "SUP001",
      supplierName: "测试供应商1",
      supplier_Contacts: "张三",
      supplier_Phone: "13800138001",
      purchase_Id: 1,
      purchase_Number: "PO001",
      sell_Id: 0,
      sell_Number: "",
      product_Id: 1,
      product_Number: "P001",
      product_Name: "测试产品1",
      specifications: "规格1",
      batch: "B001",
      price: "100.00",
      warehouse_InOrOutCount: 50,
      total_Price: 5000,
      warehouse_ID: 1,
      warehouse_Name: "主仓库",
      storage_ID: 1,
      storage_Name: "A区",
      notes: "测试入库",
      state: "已审核",
      reviewer: "审核员",
      reason: "",
      reviewTime: "2024-01-01 10:00:00",
      createUse: 1,
      upDateUse: 1,
      createTime: "2024-01-01 09:00:00",
      upDataTime: "2024-01-01 10:00:00",
      isDeleted: false,
    },
    {
      id: 2,
      warehouseType: 2, // 出库
      warehouse_Code: "WH002",
      warehousing_Type: "销售出库",
      orderCode: "SO001",
      supplierCode: "SUP002",
      supplierName: "测试供应商2",
      supplier_Contacts: "李四",
      supplier_Phone: "13800138002",
      purchase_Id: 0,
      purchase_Number: "",
      sell_Id: 1,
      sell_Number: "SO001",
      product_Id: 2,
      product_Number: "P002",
      product_Name: "测试产品2",
      specifications: "规格2",
      batch: "B002",
      price: "200.00",
      warehouse_InOrOutCount: 30,
      total_Price: 6000,
      warehouse_ID: 1,
      warehouse_Name: "主仓库",
      storage_ID: 2,
      storage_Name: "B区",
      notes: "测试出库",
      state: "已审核",
      reviewer: "审核员",
      reason: "",
      reviewTime: "2024-01-01 11:00:00",
      createUse: 1,
      upDateUse: 1,
      createTime: "2024-01-01 10:30:00",
      upDataTime: "2024-01-01 11:00:00",
      isDeleted: false,
    },
  ];

  console.log("模拟后端数据:", mockBackendData);

  // 模拟SignalR数据接收处理
  const processedData: EnterOutDTO[] = mockBackendData.map((item, index) => {
    const processed: EnterOutDTO = {
      id: item.id,
      WarehouseType: item.warehouseType,
      Warehouse_Code: item.warehouse_Code,
      Warehousing_Type: item.warehousing_Type,
      OrderCode: item.orderCode,
      SupplierCode: item.supplierCode,
      SupplierName: item.supplierName,
      Supplier_Contacts: item.supplier_Contacts,
      Supplier_Phone: item.supplier_Phone,
      Purchase_Id: item.purchase_Id,
      Purchase_Number: item.purchase_Number,
      Sell_Id: item.sell_Id,
      Sell_Number: item.sell_Number,
      Product_Id: item.product_Id,
      Product_Number: item.product_Number,
      Product_Name: item.product_Name,
      Specifications: item.specifications,
      Batch: item.batch,
      Price: item.price,
      WarehouseInOrOutCount: item.warehouse_InOrOutCount,
      Total_Price: item.total_Price,
      Warehouse_ID: item.warehouse_ID,
      Warehouse_Name: item.warehouse_Name,
      Storage_ID: item.storage_ID,
      Storage_Name: item.storage_Name,
      Notes: item.notes,
      State: item.state,
      Reviewer: item.reviewer,
      Reason: item.reason,
      ReviewTime: item.reviewTime,
      CreateUse: item.createUse,
      UpdateUse: item.upDateUse,
      CreateTime: item.createTime,
      UpdateTime: item.upDataTime,
      IsDeleted: item.isDeleted,
    };
    console.log(`处理第${index + 1}条数据:`, processed);
    return processed;
  });

  // 设置数据
  enterOutData.value = processedData;

  // 立即检查数据是否正确设置
  console.log("设置后的数据:", enterOutData.value);
  console.log("数据长度:", enterOutData.value.length);

  if (enterOutData.value.length > 0) {
    console.log("第一条数据检查:", {
      id: enterOutData.value[0].id,
      Warehouse_Code: enterOutData.value[0].Warehouse_Code,
      WarehouseInOrOutCount: enterOutData.value[0].WarehouseInOrOutCount,
      WarehouseType: enterOutData.value[0].WarehouseType,
      Warehouse_Name: enterOutData.value[0].Warehouse_Name,
      CreateTime: enterOutData.value[0].CreateTime,
      Total_Price: enterOutData.value[0].Total_Price,
    });
  }

  updateAnalysisData(processedData);

  ElMessage.success(`已生成 ${processedData.length} 条测试数据`);
};

// 调试数据映射
const debugDataMapping = () => {
  console.log("=== 调试数据映射 ===");
  console.log("当前enterOutData.value:", enterOutData.value);
  console.log("数据长度:", enterOutData.value.length);

  if (enterOutData.value.length > 0) {
    const firstItem = enterOutData.value[0];
    console.log("第一条数据完整结构:", firstItem);
    console.log("关键字段检查:");
    console.log("- id:", firstItem.id, "类型:", typeof firstItem.id);
    console.log(
      "- WarehouseType:",
      firstItem.WarehouseType,
      "类型:",
      typeof firstItem.WarehouseType
    );
    console.log(
      "- Warehouse_Code:",
      firstItem.Warehouse_Code,
      "类型:",
      typeof firstItem.Warehouse_Code
    );
    console.log(
      "- WarehouseInOrOutCount:",
      firstItem.WarehouseInOrOutCount,
      "类型:",
      typeof firstItem.WarehouseInOrOutCount
    );
    console.log(
      "- Warehouse_Name:",
      firstItem.Warehouse_Name,
      "类型:",
      typeof firstItem.Warehouse_Name
    );
    console.log(
      "- CreateTime:",
      firstItem.CreateTime,
      "类型:",
      typeof firstItem.CreateTime
    );
    console.log(
      "- Total_Price:",
      firstItem.Total_Price,
      "类型:",
      typeof firstItem.Total_Price
    );

    // 检查表格绑定的字段
    console.log("表格绑定字段检查:");
    console.log("- 表格数据源:", enterOutData.value);
    console.log("- 表格列定义:");
    console.log('  - ID列: prop="id"');
    console.log('  - 单号列: prop="Warehouse_Code"');
    console.log('  - 数量列: prop="WarehouseInOrOutCount"');
    console.log('  - 类型列: prop="WarehouseType"');
    console.log('  - 仓库列: prop="Warehouse_Name"');
    console.log('  - 类型名称列: prop="Warehouse_Type"');
    console.log('  - 日期时间列: prop="CreateTime"');
    console.log('  - 金额列: prop="Total_Price"');

    alert(
      `数据映射调试完成\n数据长度: ${enterOutData.value.length}\n请查看控制台获取详细信息`
    );
  } else {
    alert('当前没有数据，请先点击"测试数据"生成数据');
  }
};

// 调试SignalR连接
const debugSignalRConnection = () => {
  console.log("=== 调试SignalR连接 ===");

  // 检查SignalR服务状态
  const connection = signalRService.getConnection();
  const connectionStatus = signalRService.getConnectionStatus();

  console.log("SignalR连接实例:", connection);
  console.log("连接状态:", connectionStatus);

  if (connection) {
    console.log("连接ID:", connection.connectionId);
    console.log("连接状态:", connection.state);
    console.log("连接URL:", connection.baseUrl);

    // 测试发送消息到后端
    console.log("尝试发送测试消息到后端...");
    connection
      .invoke("WareHub", [])
      .then(() => {
        console.log("测试消息发送成功");
      })
      .catch((error) => {
        console.error("测试消息发送失败:", error);
      });
  } else {
    console.log("SignalR连接实例不存在");
  }

  // 检查当前数据状态
  console.log("当前enterOutData长度:", enterOutData.value.length);
  console.log("当前analysisData:", analysisData);

  alert(
    `SignalR连接调试完成\n连接状态: ${connectionStatus}\n数据长度: ${enterOutData.value.length}\n请查看控制台获取详细信息`
  );
};

// 测试SignalR连接
const testSignalR = async () => {
  console.log("测试SignalR连接状态:", connectionStatus.value);
  console.log("当前数据长度:", enterOutData.value.length);
  console.log("分析数据:", analysisData);

  // 主动请求后端推送数据
  try {
    const response = await fetch(
      "http://47.96.9.93:8000/storageread/api/SignalR/GetWarehub"
    );
    if (response.ok) {
      const result = await response.text();
      console.log("后端推送响应:", result);
      ElMessage.success("已请求后端推送数据，请查看是否收到");
    } else {
      console.error("请求后端推送失败:", response.status);
      ElMessage.error("请求后端推送失败");
    }
  } catch (error) {
    console.error("请求后端推送出错:", error);
    ElMessage.error("请求后端推送出错");
  }
};

// 生命周期
onMounted(async () => {
  await connectSignalR();

  // 页面加载后主动请求一次后端数据
  setTimeout(async () => {
    try {
      const response = await fetch(
        "http://121.196.219.73:5272/api/SignalR/GetWarehub"
      );
      if (response.ok) {
        const result = await response.text();
        console.log("页面初始化时请求后端推送响应:", result);
      } else {
        console.error("页面初始化时请求后端推送失败:", response.status);
      }
    } catch (error) {
      console.error("页面初始化时请求后端推送出错:", error);
    }
  }, 2000); // 延迟2秒，确保SignalR连接已建立
});

onUnmounted(async () => {
  await signalRService.stopConnection();
});
</script>

<style scoped>
.enter-out-analysis {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.in-icon {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.out-icon {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.net-icon {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value.positive {
  color: #67c23a;
}

.stat-value.negative {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  height: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.top-products-card {
  margin-bottom: 20px;
}

.top-products-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.product-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.product-rank {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.product-quantity {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
  font-size: 14px;
}
</style>
